const Service = require("egg").Service;

class Shopping_Cart extends Service {
  // 向购物车表中添加用户id 和 商品id
  async addShoppingCarte() {
    let { shop_id, user_id, quantity } = this.ctx.request.body;

    try {
      // 判断用户选择的商品是否存在
      if (
        await this.app.model.ShoppingCart.findOne({
          where: { shop_id, user_id }
        })
      ) {
        return {
          msg: "选择的商品已在购物车中"
        };
      }

      let res = await this.app.model.ShoppingCart.create({
        shop_id,
        user_id,
        quantity
      });

      if (!res)
        return {
          msg: "添加失败"
        };

      return {
        msg: "添加成功"
      };
    } catch (e) {
      return {
        msg: "请传入正确的参数"
      };
    }
  }
  // 用户删除购物车中的商品
  async deleteShoppingCarte() {
    let id = this.ctx.params.id;
    let res = await this.app.model.ShoppingCart.destroy({ where: { id } });
    if (!res) return { msg: "删除失败" };

    return {
      msg: "删除成功"
    };
  }

  // 修改购物车中商品的数量
  async updateCartQuantity() {
    let id = this.ctx.params.id;
    let quantity = this.ctx.request.body.quantity;

    let res = await this.app.model.ShoppingCart.update(
      { quantity },
      {
        where: {
          id
        }
      }
    );

    if (!res) return { msg: "修改失败" };

    return {
      msg: "修改成功"
    };
  }

  // 根据用户id查询购物车列表
  async queryCartListById() {
    // let user_id = this.ctx.request.body.user_id;
    // console.log(user_id);

    let url = this.ctx.request.url;

    let user_id = url.match(/=(\S*)/)[1];

    try {
      let resShop = await this.app.model.ShoppingCart.findAll({
        where: {
          user_id
        },
        include: {
          model: this.app.model.Commodity,
          as: "shop"
        }
      });
      if (!resShop) return { msg: "查询失败" };

      return resShop;
    } catch (e) {
      console.log(e);
    }
  }
}
module.exports = Shopping_Cart;
